package client

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"
	"stlswm/goali/dingtalk/request"
	"stlswm/goali/dingtalk/response"
	"strconv"
	"time"
)

type DefaultDingTalkClient struct {
	url    string
	secret string
}

//执行请求
func (c *DefaultDingTalkClient) ExecuteJsonReq(request request.Request) (error, *response.OApiRobotSendResponse) {
	reqUrl := c.url
	if c.secret != "" {
		timestamp := strconv.FormatInt(time.Now().UnixNano()/1e6, 10)
		stringToSign := timestamp + "\n" + c.secret
		h := hmac.New(sha256.New, []byte(c.secret))
		h.Write([]byte(stringToSign))
		sign := base64.StdEncoding.EncodeToString(h.Sum(nil))
		sign = url.QueryEscape(sign)
		reqUrl += "&timestamp=" + timestamp + "&sign=" + sign
	}
	req, err := http.NewRequest("POST", reqUrl, bytes.NewBuffer(request.ExportJsonParams()))
	if err != nil {
		return err, nil
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return err, nil
	}
	defer req.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	res := &response.OApiRobotSendResponse{}
	err = json.Unmarshal(body, res)
	if err != nil {
		return err, nil
	}
	return nil, res
}

//获取实例
func NewDefaultDingTalkClient(url string) DefaultDingTalkClient {
	return DefaultDingTalkClient{
		url: url,
	}
}

//获取带签名的实例
func NewDefaultDingTalkClientWithSign(url string, secret string) DefaultDingTalkClient {
	return DefaultDingTalkClient{
		url:    url,
		secret: secret,
	}
}
